package com.zdkj.subway.support.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.common.core.constant.enums.LogFunctionTypeEnum;
import com.zdkj.common.core.util.R;
import com.zdkj.common.data.mybatis.wrapper.CustomQueryWrapper;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.annotation.Inner;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.subway.support.common.cycle.*;
import com.zdkj.subway.support.dto.in.SwStOperateLogDTO;
import com.zdkj.subway.support.dto.out.ModelDTO;
import com.zdkj.subway.support.entity.SwStLogSet;
import com.zdkj.subway.support.entity.SwStOperateLog;
import com.zdkj.subway.support.service.SwStLogSetService;
import com.zdkj.subway.support.service.SwStOperateLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;


/**
 * 票务日志表
 *
 * @author cui_com
 * @date 2020-01-08 17:21:51
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swstoperatelog")
@Api(value = "swstoperatelog", tags = "票务日志表管理")
public class SwStOperateLogController {

    private final SwStOperateLogService swStOperateLogService;
    private final SwStLogSetService swStLogSetService;
    private final Map<String, Cycle> cycleMap = new HashMap<String, Cycle>() {{
        put(CycleEnum.MINUTE.getValue(), new MinuteCycleHandler());
        put(CycleEnum.HOUR.getValue(), new HourCycleHandler());
        put(CycleEnum.DAY.getValue(), new DayCycleHandler());
        put(CycleEnum.WEEK.getValue(), new WeekCycleHandler());
        put(CycleEnum.MONTH.getValue(), new MonthCycleHandler());
        put(CycleEnum.SEASON.getValue(), new SeasonCycleHandler());
        put(CycleEnum.YEAR.getValue(), new YearCycleHandler());
    }};


    @ApiOperation(value = "日志模块列表", notes = "日志模块列表")
    @GetMapping("/model/list")
    public R getModelList() {
        List<ModelDTO> list = new ArrayList<>();
        Arrays.asList(LogFunctionTypeEnum.values()).forEach(record -> {
            ModelDTO model = new ModelDTO();
            BeanUtils.copyProperties(record, model);
            list.add(model);
        });
        return R.ok(list);
    }

    @ApiOperation(value = "详细分页查询", notes = "详细分页查询")
    @GetMapping("/detail/page")
    public R getSwStAlterLogDetailPage(Page page, SwStOperateLogDTO stationDetaiDTO) {
        return R.ok(swStOperateLogService.queryDetailByPage(page, new CustomQueryWrapper(SwStOperateLog.class)
                .addDTO(stationDetaiDTO)
                .init()));
    }

    /**
     * 分页查询
     *
     * @param page           分页对象
     * @param swStOperateLog 票务日志表
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getSwStOperateLogPage(Page page, SwStOperateLog swStOperateLog) {
        List<String> dateCondition = swStOperateLog.getDates1();
        String code = swStOperateLog.getCreatorCode();
        swStOperateLog.setCreatorCode(null);
        LambdaQueryWrapper<SwStOperateLog> queryWrapper = Wrappers.query(swStOperateLog).lambda();
        if (ObjectUtil.isNotEmpty(dateCondition)) {
            queryWrapper.between(SwStOperateLog::getRecordTime, dateCondition.get(0), dateCondition.get(1));
        }
        if (StringUtils.isNotBlank(code)) {
            queryWrapper.like(SwStOperateLog::getCreatorCode, code);
        }
        return R.ok(swStOperateLogService.page(page, queryWrapper));
    }


    /**
     * 通过id查询票务日志表
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Long id) {
        return R.ok(swStOperateLogService.getById(id));
    }

    /**
     * 新增票务日志表
     *
     * @param swStOperateLog 票务日志表
     * @return R
     */
    @ApiOperation(value = "新增票务日志表", notes = "新增票务日志表")
    @PostMapping
    public R save(@RequestBody SwStOperateLogDTO swStOperateLog) {
        SwStOperateLog defaultObj = ObjectUtils.getDefaultObj(SwStOperateLog.class);
        BeanUtils.copyProperties(swStOperateLog, defaultObj);
        return R.ok(swStOperateLogService.save(defaultObj));
    }

    /**
     * 批量新增票务日志表
     *
     * @param logDtoList 票务日志表
     * @return R
     */
    @ApiOperation(value = "新增票务日志表", notes = "新增票务日志表")
    @PostMapping("/saveBatch")
    public R saveBatch(@RequestBody List<SwStOperateLogDTO> logDtoList) {
        ArrayList<SwStOperateLog> logList = new ArrayList<>();
        for (SwStOperateLogDTO swStOperateLogDTO : logDtoList) {
            SwStOperateLog defaultObj = ObjectUtils.getDefaultObj(SwStOperateLog.class);
            BeanUtils.copyProperties(swStOperateLogDTO, defaultObj, ObjectUtils.getNullAndEmptyPropertyNames(swStOperateLogDTO));
            logList.add(defaultObj);
        }
        return R.ok(swStOperateLogService.saveBatch(logList));
    }

    /**
     * 归档票务日志
     *
     * @param logIds
     * @return
     */
    @ApiOperation(value = "归档票务日志", notes = "归档票务日志")
    @PostMapping("/recordBatch")
    @PreAuthorize("@pms.hasPermission('support_sw_st_operate_log_record')")
    public R recordBatch(@RequestBody List<Integer> logIds) {
        return R.ok(swStOperateLogService.recordLogByIds(logIds));
    }


    /**
     * 修改票务日志表
     *
     * @param swStOperateLog 票务日志表
     * @return R
     */
    @ApiOperation(value = "修改票务日志表", notes = "修改票务日志表")
    @SysLog("修改票务日志表")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('support_sw_st_operate_log_edit')")
    public R updateById(@RequestBody SwStOperateLogDTO swStOperateLog) {
        SwStOperateLog obj = new SwStOperateLog();
        BeanUtils.copyProperties(swStOperateLog, obj);
        return R.ok(swStOperateLogService.updateById(obj));
    }


    /**
     * 通过id删除票务日志表
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除票务日志表", notes = "通过id删除票务日志表")
    @SysLog("通过id删除票务日志表")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('support_sw_st_operate_log_del')")
    public R removeById(@PathVariable Long id) {
        return R.ok(swStOperateLogService.removeById(id));
    }

    /**
     * 批量删除票务日志表
     *
     * @param ids ids
     * @return R
     */
    @ApiOperation(value = "批量删除票务日志表", notes = "批量删除票务日志表")
    @SysLog("批量删除票务日志表")
    @DeleteMapping("/delBatch")
    @PreAuthorize("@pms.hasPermission('support_sw_st_operate_log_delBatch')")
    public R removeByIds(@RequestBody List<Long> ids) {
        return R.ok(swStOperateLogService.removeByIds(ids));
    }

    /**
     * 内部调用触发，可根据日志设置进行日志删除
     *
     * @return
     */
    @Inner
    @ApiOperation(value = "通过日志配置进行归档", notes = "通过日志配置进行归档")
    @GetMapping("/task/log-set")
    public R recordByLogSet() {
        List<SwStLogSet> listSet = swStLogSetService.list();
        if (listSet.isEmpty()) {
            return R.failed("log-set null");
        }
        SwStLogSet logSet = listSet.get(0);
        LocalDateTime endDateTime = cycleMap.get(logSet.getSaveCycle())
                .getLogEndDate(Integer.parseInt(logSet.getCycleValue()));
        Integer result = swStOperateLogService.recordLogByLogSet(endDateTime);
        return R.ok(result);
    }


}
